package edu.rmit.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.swing.JTextArea;

import edu.rmit.service.IChatService;
import edu.rmit.service.IMessageService;
import edu.rmit.util.PromotDialog;

/**
 * The class is to deal with when a user clicked the send forum message button
 * send. And the forum message will aslo be save to the database.
 * 
 * @author Thaw Zin
 * @version 1.0
 */
public class ListenerSendForumMsg implements ActionListener {

	/**
	 * The message edit panel which the forum list is displayed on it.
	 */
	private MessageEditorPanel messagePanel;

	/**
	 * The client instance which provide the service.
	 */
	private Client client;

	/**
	 * The group id which the forum message belongs to.
	 */
	private int groupId;

	/**
	 * The user name of user who have send this forum message
	 */
	private String userName;

	/**
	 * The constructor which is to construct a corresponding listener class
	 * which deal with the forum message send.
	 * 
	 * @param client
	 *            The client instance which provide the service.
	 * @param messagePanel
	 *            The message edit panel which the forum list is displayed on
	 *            it.
	 * @param groupId
	 *            The group id which the forum message belongs to.
	 * @param userName
	 *            The user name of user who have send this forum message
	 */
	public ListenerSendForumMsg(Client client, MessageEditorPanel messagePanel,
			int groupId, String userName) {
		this.client = client;
		this.messagePanel = messagePanel;
		this.groupId = groupId;
		this.userName = userName;
	}

	/**
	 * This is method is to perform the logic when a user click the message send
	 * button. Which will use CallBackServiceImpl to send this message to all
	 * the participant who currently is participanted into this group.
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		JTextArea messageArea = messagePanel.getTaEditor();
		String message = messageArea.getText().trim(); 
		try {
			if (!message.equals("")) {
				IChatService chatService = client.getChatService();
				IMessageService messageService = client.getMessageService();
				chatService.sendForumMessage(groupId, userName, message);
				messageService.addMessage(groupId, message, userName);
				messageArea.setText("");
			} else {
				PromotDialog.errorMessageBox(null, "Error",
						"Forum message is not allowed empty!");
			}
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
	}

}
